from django.db import models
from books.models import Book, BookNote
from articles.models import Article, ArticleNote
from datetime  import datetime, timedelta
from django.contrib.auth.models  import User
from django.db.models.query import QuerySet

def today():
    now   = datetime.now()
    start = datetime.min.replace(year = now.year,
                                 month = now.month,
                                 day = now.day)
    end   = (start + timedelta(days = 30)) - timedelta.resolution
    return (start,end)

class ThoughtQuerySet(QuerySet):
    def today(self):
        return self.filter(creation_date__range = today())
 
class ThoughtManger(models.Manager):
    def get_query_set(self):
        return ThoughtQuerySet(self.model)
    def today(self):
        return self.get_query_set().today()


class Thought(models.Model):
    title         =  models.CharField(max_length = 50)
    description   =  models.TextField()
    creation_date =  models.DateTimeField(default = datetime.now)
    start_date    =  models.DateTimeField(null = True,blank = True)
    inventor      =  models.ForeignKey(User, related_name = 'Thought_inventor_set')
    witnessess    =  models.ManyToManyField(User,through = "Witness")
    article_notes =  models.ManyToManyField(ArticleNote,blank=True)
    book_notes    =  models.ManyToManyField(BookNote,blank=True)
    latest        =  models.BooleanField(default = True)
    published     =  models.BooleanField(default = False)
    published_date=  models.DateTimeField(default = datetime.now)
 
    LEVEL_CHOICES = (
     (u'Mr',  u'Mister'),
     (u'Mrs', u'Missis'),
     (u'Dr',  u'Doctor'),
     (u'Prof', u'Professor'),
     (u'St', u'Student'),
    ) 
    education_level = models.CharField(max_length = 5, choices = LEVEL_CHOICES) 
    
    objects       =  ThoughtManger()
     
    # extract a snippet text from the thought discription 
    def snippet(self):
        sn = self.description
        lsn = sn.lower()
        if ((len(lsn) % 100 < len(lsn))):
            lsn = lsn[:100]
        sn  = lsn + '...'
        return(sn)         

    #overwrite the __unicode__ method
    def __unicode__(self):
        return self.title
     
    # overwrite the save method to save in a different manner
    def save(self, **kwargs):
        Thought.objects.filter(latest = True, 
            inventor = self.inventor).today().update(latest = False)
        super(Thought,self).save(**kwargs)
    
   
class  Witness(models.Model):
    user =  models.ForeignKey(User)
    thought =  models.ForeignKey(Thought)
    registration_date = models.DateTimeField(default = datetime.now)
    
    def __unicode__(self):
        return " %s is witnessing the %s " % (self.user.username, self.Thought)  
    
    class Meta(object):
        verbose_name_plural = "Witnesses"
